<?php


namespace app\admin\validate;

use think\Validate;

/**
 * 分类验证器
 * Class GoodsCategory
 * @package app\shop\validate
 * @author Mr.Liu
 * @create 2021-11-02 14:23
 */
class GoodsCategory extends Validate
{

    /**
     * 验证规则
     * @var string[]
     */
    protected $rule = [
        'name' => 'require|is_cage_unique:shop_goods_category|max:10|min:1',
    ];

    /**
     * 错误信息
     * @var string[]
     */
    protected $message = [
        'name.is_cage_unique'   => '分类名称已经存在',
        'name.require'          => '请填写分类名称',
        'name.max'              => '分类名称最多填写10个字符',
        'name.min'              => '请填写分类名称',
    ];



    /**
     * 验证name唯一性
     * @param $value
     * @param $rule
     * @param array $data
     * @param string $field
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author Mr.Li
     * @create 2021-06-10 13:45
     */

    public function is_cage_unique($value, $rule, array $data = [], string $field = ''): bool
    {
        $id = $data['id'] ?? 0;
        $where = [
            ['delete_time','=',0],
            ['name','=',trim($value)],
        ];
        if($id){
            $where[] = ['id','<>',$id];
        }

        if(\app\admin\model\GoodsCategory::where($where)->value('id')){

            return false;
        }
        return true;

    }

}
